package ServiceThread;

import ServiceProvider.*;
import ServiceProvider.BcMesParser.MessageType;
import java.util.*;

public class ListenBcThread extends Thread {
	
	private boolean ifStopThread = true;
	
	private BroadcastListener bcListener;
	private BcMesHandler bcMesHandler;
	private BcMesParser bcMesParser;
	
	public ListenBcThread(String port, String listenGroup) {
		this.bcListener = new BroadcastListener(port, listenGroup);
		this.bcMesHandler = new BcMesHandler();
		this.bcMesParser = new BcMesParser();
	}

	@Override
	public void run() {
		while (ifStopThread) {
			String message = bcListener.receiveBroadcastMessage();
			
			Map<String, String> parsedMes = bcMesParser.parseMessage(message);
			String header = parsedMes.get("header");
			String content = parsedMes.get("content");
			
			MessageType mesType = bcMesParser.parseMessageHeaderForType(header);
			
			switch (mesType) {
				case HOSTSTATE: {
					Map<String, String> infos = bcMesParser.parseContentForHostInfos(content);
					bcMesHandler.handleHostStateMessage(infos);
					break;
				}
				case CHAT:
					bcMesHandler.handleChatMessage(content); break;
			}
		}
	}
	
}
